package com.fh.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fh.utils.ResultState;
import com.fh.vo.ResultVo;
import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class CheckTokenInterceptor  implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    String method=request.getMethod();
    if ("OPTIONS".equalsIgnoreCase(method)){
        return  true;
    }

        String token = request.getParameter("token");
          if (token==null){
              ResultVo resultVo = new ResultVo(ResultState.LOGIN_NO, "请先登录！aaaaaa!! ", null);
              doResponse(response,resultVo);
          }else {
              try {
                  JwtParser parser = Jwts.parser();
                  parser.setSigningKey("xukun");
                  Jws<Claims> claimsJws = parser.parseClaimsJws(token);
                  return true;
              }catch (ExpiredJwtException e){
                  ResultVo resultVo = new ResultVo(ResultState.LOGIN_GUOQI, "登录过期，请重新登录！ ",
                          null);
                  doResponse(response,resultVo);
              }catch (UnsupportedJwtException e){
                  ResultVo resultVo = new ResultVo(ResultState.LOGIN_NO, "Token不合法，请⾃重！ ",
                          null);
                  doResponse(response,resultVo);
              }catch (Exception e){
                  ResultVo resultVo = new ResultVo(ResultState.LOGIN_NO, "请先登录！ ", null);
                  doResponse(response,resultVo);
              }
          }

        return false;
    }


    private void doResponse(HttpServletResponse response,ResultVo resultVo) throws
            IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        String s = new ObjectMapper().writeValueAsString(resultVo);
        out.print(s);
        out.flush();
        out.close();
    }
}
